﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SumiaAccountBook.SubControls
{  

    /// <summary>
    /// UCCashFlow.xaml 的交互逻辑
    /// </summary>
    public partial class UCCashFlow : UserControl
    {
        const int PageSize = 20;
        private int page_count = 1;

        const string DEF_ADD_VAL = "-全部-";
        const string DEF_SEARCH_VAL = "-未选择-";

        Biz.KVKeyValue kv = new Biz.KVKeyValue();
        Biz.KVGoingProject kvGoingProject = new Biz.KVGoingProject();
        Biz.KVProject kvProject = new Biz.KVProject(); 
        Biz.KVStaff kvStaff = new Biz.KVStaff();
        Biz.KVAccountBook kvAccount = new Biz.KVAccountBook();
        Dictionary<object, string> dict = new Dictionary<object, string>();

        public ProjectInfoProvider MySearchProviderEng { 
            get
            {
                
                var list=DataAccess.DaCommon<DataAccess.Entity.Project>.GetAll();
                foreach (var val in list)
                {
                    this.dict.Add(val.Key, val.Name);
                }
                return new ProjectInfoProvider(this.dict); 
            } 
        }

        public UCCashFlow()
        {
            InitializeComponent();

            this.dp_date.Text = DateTime.Now.ToString();

            bindDefault();
        }   

        private void bindDefault()
        {
            var list_Type = Biz.KVConstHelper.GetInstance().GetAllValue<Biz.KVCashFlowType>();
            this.cb_type.ItemsSource = list_Type;
            this.cb_type.SelectedIndex = 1;

            List<string> list_Type_s = new List<string> { DEF_SEARCH_VAL };
            list_Type_s.AddRange(list_Type);
            this.cb_type_search.ItemsSource = list_Type_s;
            this.cb_type_search.SelectedIndex = 0;

            var list_category = this.kv.GetValues(this.cb_type.SelectedValue as string);
            this.cb_category.ItemsSource = list_category;
            this.cb_category.SelectedIndex = 0;

            var list_project = this.kvGoingProject.GetAllValue();
            List<string> list_project_new = new List<string> { DEF_ADD_VAL };
            list_project_new.AddRange(list_project);
            this.cb_project.ItemsSource = list_project_new;
            this.cb_project.SelectedIndex = 0;            

            List<string> list_staff = this.kvStaff.GetAllValue();
            List<string> list_staff_new = new List<string> { DEF_ADD_VAL };
            list_staff_new.AddRange(list_staff);
            this.cb_staff.ItemsSource = list_staff_new;
            this.cb_staff.SelectedIndex = 0;

            List<string> list_staff_search = new List<string> { DEF_SEARCH_VAL };
            list_staff_search.AddRange(list_staff);
            this.cb_staff_search.ItemsSource = list_staff_search;
            this.cb_staff_search.SelectedIndex = 0;

            this.cb_accountbook.ItemsSource = this.kvAccount.GetAllValue();
            this.cb_accountbook.SelectedIndex = 0;

            this.cb_accountbook_search.ItemsSource = this.cb_accountbook.ItemsSource;
            this.cb_accountbook_search.SelectedIndex = 0;

            bindData();
            this.DataContext = this;
        }

        private void bindData()
        {
            //组织查询条件
            int type_s = 0;
            var tmpStr = this.cb_type_search.SelectedValue as string;
            if (!string.IsNullOrEmpty(tmpStr) && tmpStr != DEF_SEARCH_VAL)
            {
                type_s = Biz.KVConstHelper.GetInstance().GetKey<Biz.KVCashFlowType>(this.cb_type_search.SelectedValue as string);
            }
            int category_s = -1;
            if (this.cb_category_search.SelectedValue != null)
            {
                category_s = this.kv.GetKey(this.cb_category_search.SelectedValue as string);
            }
            DateTime date_start = DateTime.MinValue;
            if (!string.IsNullOrEmpty(this.dp_date_start_search.Text.Trim()))
            {
                date_start = Convert.ToDateTime(this.dp_date_start_search.Text.Trim());
            }
            DateTime date_end = DateTime.MinValue;
            if (!string.IsNullOrEmpty(this.dp_date_end_search.Text.Trim()))
            {
                date_end = Convert.ToDateTime(this.dp_date_end_search.Text.Trim());
            }
            int projectID_s = -1;
            var tmpProjectId = this.auto_project_search.SelectedListBoxValue;
            if (null != tmpProjectId)
            {
                projectID_s = Convert.ToInt32(tmpProjectId);
            }
            int staffId_s = -1;
            tmpStr = this.cb_staff_search.SelectedValue as string;
            if (!string.IsNullOrEmpty(tmpStr) && tmpStr != DEF_SEARCH_VAL)
            {
                staffId_s = this.kvStaff.GetKey(this.cb_staff_search.SelectedValue as string);
            }
            int accountbook_Id = -1;
            if (!string.IsNullOrEmpty(this.cb_accountbook_search.SelectedValue as string))
            {
                accountbook_Id = this.kvAccount.GetKey(this.cb_accountbook_search.SelectedValue as string);
            }

            int t1 = 0;
            List<DataAccess.Entity.CashFlow> tmpList = DataAccess.DaCashFlow.GetList(page_count, PageSize,
                accountbook_Id, type_s, category_s, date_start, date_end, projectID_s, staffId_s, ref t1);
            List<Biz.CashFlowObj> list = new List<Biz.CashFlowObj>();
            if (null != tmpList && tmpList.Count > 0)
            {

                string type = string.Empty;
                string cat = string.Empty;
                string project = string.Empty;
                string staff = string.Empty;
                string accountBook = string.Empty;
                foreach (var entity in tmpList)
                {
                    type = Biz.KVConstHelper.GetInstance().GetValue<Biz.KVCashFlowType>(entity.Type);
                    cat = this.kv.GetValue(entity.Category);
                    project = this.kvProject.GetValue(entity.ProjectId);
                    staff = this.kvStaff.GetValue(entity.StaffId);
                    accountBook = this.kvAccount.GetValue(entity.AccountBookId);
                    list.Add(
                        new Biz.CashFlowObj
                        {
                            Key = entity.Key,
                            Type = type,
                            Category = cat,
                            Amount = entity.Amount,
                            InitDate = entity.Date,
                            Project = project,
                            Staff = staff,
                            AccountBook = accountBook,
                            Memo = entity.Memo
                        });
                }



                decimal incomeTotal = DataAccess.DaCashFlow.GetTotal(accountbook_Id, (int)Biz.KVCashFlowType.emCashFlowType.In, category_s, date_start, date_end, projectID_s, staffId_s);
                decimal outcomeTotal = DataAccess.DaCashFlow.GetTotal(accountbook_Id, (int)Biz.KVCashFlowType.emCashFlowType.Out, category_s, date_start, date_end, projectID_s, staffId_s);
                this.lb_sm.Text = "总收入:" + incomeTotal + "，总支出" + outcomeTotal;
            }
            else
            {
                this.lb_sm.Text = "没有符合条件的记录";
            }

            this.dg.ItemsSource = list;
            this.dp.TotalCount = t1;
        }

        private void btn_cashflow_add_Click(object sender, RoutedEventArgs e)
        {
            int type = Biz.KVConstHelper.GetInstance().GetKey<Biz.KVCashFlowType>(this.cb_type.SelectedValue as string);
            int Category = this.kv.GetKey(this.cb_category.SelectedValue as string);
            decimal amount = 0;
            if (!decimal.TryParse(this.tb_amount.Text.Trim(), out amount))
            {
                MessageBox.Show("金额应该填写数字！");
                return;
            }
            DateTime dt = DateTime.MinValue;
            if (!string.IsNullOrEmpty(this.dp_date.Text.Trim()))
            {
                dt = Convert.ToDateTime(this.dp_date.Text.Trim());
            }
            else
            {
                MessageBox.Show("请填写日期！");
                return;
            }
            int ProjectId = -1;
            var tmpStr = this.cb_project.SelectedValue as string;
            if (!string.IsNullOrEmpty(tmpStr) && tmpStr != DEF_ADD_VAL)
            {
                ProjectId = this.kvProject.GetKey(this.cb_project.SelectedValue as string);
            }
            int StaffId = -1;
            tmpStr = this.cb_staff.SelectedValue as string;
            if (!string.IsNullOrEmpty(tmpStr) && tmpStr != DEF_ADD_VAL)
            {
                StaffId = this.kvStaff.GetKey(this.cb_staff.SelectedValue as string);
            }
            int AccountBookId = -1;
            if (!string.IsNullOrEmpty(this.cb_accountbook.SelectedValue as string))
            {
                AccountBookId = this.kvAccount.GetKey(this.cb_accountbook.SelectedValue as string);
            }
            string memo = this.tb_memo.Text.Trim();

            DataAccess.Entity.CashFlow entiry = new DataAccess.Entity.CashFlow
            {
                Type = type,
                Category = Category,
                Amount = amount,
                Date = dt,
                ProjectId = ProjectId,
                StaffId = StaffId,
                AccountBookId = AccountBookId,
                Memo = memo
            };

            try
            {
                DataAccess.DaCommon<DataAccess.Entity.CashFlow>.Add(entiry);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            bindData();
        }

        private void dp_PageChanged(object sender, CubicFamily.StockTool.ComonControl.PageChangedEventArgs e)
        {
            this.page_count = e.CurrentPageIndex;
            bindData();
        }

        private void dg_cashflow_remove_Click(object sender, RoutedEventArgs e)
        {
            var original = e.OriginalSource as Button;
            var key = original.CommandParameter;
            int Id = Convert.ToInt32(key);
            MessageBoxResult confirmToDel = MessageBox.Show("确认要删除所选行吗？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (confirmToDel == MessageBoxResult.Yes)
            {
                try
                {
                    DataAccess.DaCommon<DataAccess.Entity.CashFlow>.Delete(Id);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

                bindData();
            }
        }

        private void cb_type_Selected(object sender, RoutedEventArgs e)
        {
            this.cb_category.ItemsSource = this.kv.GetValues(this.cb_type.SelectedValue as string);
            this.cb_category.SelectedIndex = 0;
        }

        private void cb_type_search_Selected(object sender, RoutedEventArgs e)
        {
            var selected = this.cb_type_search.SelectedValue as string;
            if (!string.IsNullOrEmpty(selected) && selected != DEF_SEARCH_VAL)
            {
                this.cb_category_search.ItemsSource = this.kv.GetValues(selected);
                this.cb_category_search.SelectedIndex = 0;
            }
            else
            {
                this.cb_category_search.ItemsSource = null;
            }
        }

        private void btn_search_Click(object sender, RoutedEventArgs e)
        {           
            bindData();
        }
    }
}
